package com.cdsxt.genCode.listenner;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import org.springframework.web.bind.annotation.RequestMapping;

import com.cdsxt.util.PackageUtil;

/**
 *把所有模块的查询信息的url放入servletcontext中，方便主页直接使用！
 */
public class InitModuleQueryUrlToServletContextListenner implements ServletContextListener {

	/**
	 * 获取所有模块的信息：查询url和名字
	 */
	public List<Map<String,Object>> getAllModulesQueryUrl(){
		try {
			String packageName = "com.cdsxt.controller";
			List<String> classNames = PackageUtil.getAllClassName(packageName,"Controller");
			List<Map<String,Object>> listModule = new ArrayList<Map<String,Object>>();
			for (String className : classNames) {
				System.out.println(className);
				Class ctCls=Class.forName(className);
//				System.out.println("指定注解："+ctCls.getAnnotation(RequestMapping.class));
				ModuleInfo annotation = (ModuleInfo) ctCls.getAnnotation(ModuleInfo.class);
				if (annotation==null) {
					continue;
				}
				String queryUrl= annotation.queryUrl();
				String moduleName= annotation.moduleInfo();
				Integer order= annotation.order();
				//核心模块不添加
				if (!queryUrl.startsWith("gen")) {
					Map<String, Object> module=new HashMap<String, Object>();
					module.put("queryUrl", queryUrl);
					module.put("moduleInfo", moduleName);
					module.put("order", order);
					//模块信息添加
					listModule.add(module);
				}
				Collections.sort(listModule, (Map<String,Object> o1, Map<String,Object> o2)->{
					Integer order1= (Integer) o1.get("order");
					Integer order2= (Integer) o2.get("order");
					if(order1>order2) {
						return 1;
					}
					if(order1<order2) {
						return -1;
					}
					return 0;
				});
			}
			return listModule;
		} catch (Exception e) {
			e.printStackTrace(System.out);
			System.out.println("获取所有模块==查询功能的url==错误！！！");
			return null;
		}
		
	}
	
    public void contextInitialized(ServletContextEvent sce)  {
    	//servletcontext作用域
    	ServletContext sc=sce.getServletContext();
    	List<Map<String,Object>> listModule=this.getAllModulesQueryUrl();
    	//放入作用域
    	sc.setAttribute("listModule", listModule);
    	System.out.println("【模块信息初始化完成！】");
    }
    
	/**
     * @see ServletContextListener#contextDestroyed(ServletContextEvent)
     */
    public void contextDestroyed(ServletContextEvent arg0)  { 
         // TODO Auto-generated method stub
    }

	
}
